/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package pfc.generacion;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Types;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.ddlutils.model.Database;
import pfc.comun.IDEpfc;
import pfc.comun.Proyecto;
import pfc.modelocg.CGModel;
import pfc.modeloer.ERAttrib;
import pfc.modeloer.EREntity;
import pfc.modeloer.ERModel;

/**
 *
 * @author xandru
 */
public class GeneradorValidacion {
    Proyecto _proyecto;
    Database _dbmodel;
    ERModel _erModel;
    CGModel _cgModel;
    private PrintWriter out;

    public GeneradorValidacion(Proyecto pro, Database db, ERModel er, CGModel cg) {
        this._proyecto = pro;
        this._dbmodel = db;
        this._erModel = er;
        this._cgModel = cg;
    }


    public void generar(File srcPath)
    {
        File f = new File(srcPath.getAbsolutePath() + File.separator + "validator");

        generarDir(f);

        generarClase(f,"Validator");

        

    }

    private void generarDir(File file) {
        try {
            FileUtils.forceMkdir(file);
        } catch (IOException ex) {
            Logger.getLogger(Application.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void generarMetodoValidacion(EREntity e) {

        out.println("public Iterable<String> validate(" + StringUtils.capitalize(e.getName()) + " obj)" );
        out.println("{");
        out.println("this.objeto = obj;");        
        String requeridosCode = "String[] requeridosArray= {";
        for (ERAttrib a:e.getAttribs())
        {
            if (a.isRequired())
                requeridosCode += "\"" + a.getName() + "\",";
        }

        if (requeridosCode.endsWith(","))
            requeridosCode = requeridosCode.substring(0,requeridosCode.length()-1);
        requeridosCode += "};";

        out.println(requeridosCode);
        out.println("ArrayList<String> requeridos = new ArrayList<String>(Arrays.asList(requeridosArray));");
//out.println("System.out.println(requeridos);");
        out.println("String key=\"\";");
        out.println("String value=\"\";");
        out.println("for (Iterator<String> k=attribs.iterator(),v=values.iterator();k.hasNext();){");
        out.println("try {");
        out.println("key = k.next();");
        out.println("value = v.next();");
//out.println("System.out.println(\"validando el campo: \" + key + \" con valor =  \" + value + \" campos requeridos-> \" + requeridos);");
        out.println("if (requeridos.contains(key)){");
        out.println(" if (StringUtils.isEmpty(value))");
        out.println("  errores.add(\"El campo \" + key + \" no puede ser vacio \");");
        out.println("}");
        out.println("else {");
//out.println("System.out.println(\"requerido?\"+requeridos.contains(key) + \" CONTINUE\");");
        out.println(" if (StringUtils.isEmpty(value))");
        out.println("continue;");
        out.println("}");
        
        out.println("obj.putPropertyValue(key,value);");
        out.println("} catch (Exception e)");
        out.println("{");
        out.println("errores.add(\"Error en el campo [\" + key + \"], recibido valor [\" + value + \"]. \" + e);");
        out.println("}");
        out.println("}");
        out.println("return errores;");
        out.println("}");

    }

    private void generarClase(File f, String clase) {
        IDEpfc.log("\n================Generando clase validacion =====================");
        IDEpfc.logTime("Generando clase " + clase);
        try {
            out = new PrintWriter(new FileOutputStream(f.getAbsolutePath() + File.separator + clase + ".java"));
            out.println("package " + _proyecto.nombre + ".validator;");
            out.println("import " + _proyecto.nombre + ".dto.*;");
            out.println("import java.util.ArrayList;");
            out.println("import java.util.Iterator;");
            out.println("import java.util.Arrays;");
            out.println("import org.apache.commons.lang.time.DateUtils;");
            out.println("import org.apache.commons.lang.StringUtils;");

            out.println("public class Validator {");
            out.println("private Iterable<String> attribs;");
            out.println("private Iterable<String> values;");
            out.println("ArrayList<String> errores = new ArrayList<String>();");
            out.println("BaseDTO objeto;");
            out.println("public Validator(Iterable<String> attrs,Iterable<String> vals) {");
            out.println("this.attribs = attrs;");
            out.println("this.values = vals;");
            out.println("}");
            
            for (EREntity e : this._erModel.getEntityList()) {
                generarMetodoValidacion(e);
                generarMetodoGetObjeto(e);
            }
            out.println("}");
            out.flush();
            out.close();

        } catch (FileNotFoundException ex) {
            Logger.getLogger(GeneradorValidacion.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    private void generarMetodoGetObjeto(EREntity e) {
        out.println("public " + StringUtils.capitalize(e.getName()) +" getValidatedObject("+ StringUtils.capitalize(e.getName()) + " obj)" );
        out.println("{");
        out.println("if (!errores.iterator().hasNext())");
        out.println("return (" + StringUtils.capitalize(e.getName()) + ") objeto;");
        out.println("return null;");
        out.println("}");
    }

}
